package com.blc.controller;


import com.blc.pojo.dto.CutInDTO;
import com.blc.util.EncryptSHA1Util;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@RequestMapping(path = "/cutIn")
@RestController
public class CutInController {
    private final static Logger logger = LoggerFactory.getLogger(CutInController.class);

    @Value("${wx.blc.token}")
    private String token;
    /**
     * @Author tidudada
     * @Description  公众号接入
     * @Date 上午10:15 2021/11/24
     **/
    @GetMapping
    public void cutIn(HttpServletRequest request, HttpServletResponse response){
        Map<String, String[]> cutInMap = request.getParameterMap();
        try (PrintWriter writer = response.getWriter()) {
            if (cutInMap == null || cutInMap.size() < 4) {
                throw new IllegalStateException();
            }
            CutInDTO inDto = new CutInDTO();
            BeanUtils.populate(inDto, cutInMap);
            String[] ages = {inDto.getNonce(), inDto.getTimestamp(), token};
            // 跟进微信文档需要将内容进行sha1加密后在返回
            String sha = EncryptSHA1Util.dictionariesAndSha(ages);
            if (sha.equals(inDto.getSignature())) {
                writer.write(inDto.getEchostr());
                logger.info("join up !");
            }
        } catch (IllegalStateException | IllegalAccessException | InvocationTargetException e) {
            logger.error("illegal request");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping
    public void getUserMessage(HttpServletRequest request){
        Map<String, String[]> parameterMap = request.getParameterMap();
        logger.info(parameterMap+"");
    }



}
